package com.kitfm.nook.adhoc;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.IntentService;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.widget.RemoteViews;
import android.widget.Toast;

public class AppWidget extends AppWidgetProvider {
	
	 @Override
	 public void onReceive(Context ctxt, Intent intent) {

		 if (intent.getAction()==null) {
			 ctxt.startService(new Intent(ctxt, ToggleService.class));
		 } else {
			 super.onReceive(ctxt, intent);
		 }
	 }
	
	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
		context.startService(new Intent(context, ToggleService.class));
	}

	public static class ToggleService extends IntentService {

		public ToggleService() {
			super("AppWidget$ToggleService");
		}

		@Override
		protected void onHandleIntent(Intent intent) {
			 ComponentName me=new ComponentName(this, AppWidget.class);
			 AppWidgetManager mgr=AppWidgetManager.getInstance(this);
			 mgr.updateAppWidget(me, buildUpdate(this));
		}

		private RemoteViews buildUpdate(Context context) {
			RemoteViews updateViews=new RemoteViews(context.getPackageName(),R.layout.widget);
			boolean wState = (new File("data/data/com.kitfm.nook.adhoc/files/wap")).exists();
			String FILENAME = "wap";
			String string = "AdHoc Mode Enabled!";
		    FileOutputStream fos = null;
			if(wState)
			{
				//turn Infrastructure On
				updateViews.setImageViewResource(R.id.wState, R.drawable.wap);
				deleteFile("data/data/com.kitfm.nook.adhoc/files/wap");
			} else {
				//turn Ad Hoc on
				updateViews.setImageViewResource(R.id.wState, R.drawable.wah);
				try {
					fos = openFileOutput(FILENAME, Context.MODE_WORLD_READABLE);
					fos.write(string.getBytes());
					fos.close();
				}catch (IOException e) {
					// TODO Auto-generated catch block
					Toast.makeText(context, "Write Failed", Toast.LENGTH_SHORT).show();;
				}
			}
			
			Intent i=new Intent(this, AppWidget.class);
			PendingIntent pi = PendingIntent.getBroadcast(context, 0, i,0);
			updateViews.setOnClickPendingIntent(R.id.wState,pi);
			
			return updateViews; 

		}
	}
	
}
